package com.esayread.utils

import android.content.Context
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.io.File

/**
 * 管理书籍原始路径记录的类
 * 用于记录添加到书架的书籍的原始文件路径，避免重复扫描
 */
class BookPathManager(private val context: Context) {
    
    companion object {
        private const val PATH_RECORD_FILE = "book_paths.json"
    }
    
    /**
     * 获取路径记录文件
     */
    private fun getPathRecordFile(): File {
        return File(context.filesDir, PATH_RECORD_FILE)
    }
    
    /**
     * 读取所有已记录的路径
     * @return Map<String, String> bookId -> originalPath
     */
    suspend fun getAllRecordedPaths(): Map<String, String> = withContext(Dispatchers.IO) {
        val pathMap = mutableMapOf<String, String>()
        val recordFile = getPathRecordFile()
        
        try {
            if (recordFile.exists()) {
                val jsonContent = recordFile.readText()
                if (jsonContent.isNotBlank()) {
                    val jsonObject = JSONObject(jsonContent)
                    val keys = jsonObject.keys()
                    while (keys.hasNext()) {
                        val key = keys.next()
                        pathMap[key] = jsonObject.getString(key)
                    }
                }
            }
        } catch (e: Exception) {
            Log.e("BookPathManager", "Error reading path records", e)
        }
        
        pathMap
    }
    
    /**
     * 获取所有已记录的原始路径列表
     */
    suspend fun getAllRecordedOriginalPaths(): Set<String> = withContext(Dispatchers.IO) {
        getAllRecordedPaths().values.toSet()
    }
    
    /**
     * 记录书籍的原始路径
     * @param bookId 书籍ID
     * @param originalPath 原始文件路径
     */
    suspend fun recordBookPath(bookId: String, originalPath: String) = withContext(Dispatchers.IO) {
        try {
            val pathMap = getAllRecordedPaths().toMutableMap()
            pathMap[bookId] = originalPath
            
            val jsonObject = JSONObject()
            pathMap.forEach { (id, path) ->
                jsonObject.put(id, path)
            }
            
            val recordFile = getPathRecordFile()
            recordFile.writeText(jsonObject.toString())
            
            Log.d("BookPathManager", "Recorded path for book $bookId: $originalPath")
        } catch (e: Exception) {
            Log.e("BookPathManager", "Error recording book path", e)
        }
    }
    
    /**
     * 删除书籍的路径记录
     * @param bookId 书籍ID
     */
    suspend fun removeBookPath(bookId: String) = withContext(Dispatchers.IO) {
        try {
            val pathMap = getAllRecordedPaths().toMutableMap()
            val removedPath = pathMap.remove(bookId)
            
            val jsonObject = JSONObject()
            pathMap.forEach { (id, path) ->
                jsonObject.put(id, path)
            }
            
            val recordFile = getPathRecordFile()
            recordFile.writeText(jsonObject.toString())
            
            Log.d("BookPathManager", "Removed path record for book $bookId: $removedPath")
        } catch (e: Exception) {
            Log.e("BookPathManager", "Error removing book path", e)
        }
    }
    
    /**
     * 检查路径是否已被记录
     * @param path 要检查的路径
     * @return true if path is already recorded
     */
    suspend fun isPathRecorded(path: String): Boolean = withContext(Dispatchers.IO) {
        val recordedPaths = getAllRecordedOriginalPaths()
        recordedPaths.contains(path)
    }
    
    /**
     * 清理所有路径记录（用于测试或重置）
     */
    suspend fun clearAllRecords() = withContext(Dispatchers.IO) {
        try {
            val recordFile = getPathRecordFile()
            if (recordFile.exists()) {
                recordFile.delete()
                Log.d("BookPathManager", "Cleared all path records")
            }
        } catch (e: Exception) {
            Log.e("BookPathManager", "Error clearing path records", e)
        }
    }
}